var express = require('express');
var router = express.Router();
const UserModel = require('../../module/userModule');
const md5 = require('md5');
const jwt = require('jsonwebtoken');
const { secret } = require('../../config')

router.post('/login', function (req, res, next) {
    // 获取请求体中的数据
    let { username, password } = req.body;
    // 查询数据库
    UserModel.findOne({username, password: md5(password)}).then(data => {
        if (data) {
            // 生成 jwt
            let token = jwt.sign({
                username: data.username,
                _id: data._id,
            }, secret, {
                expiresIn: 60 * 60 *24 * 7 // 过期时间
            })

            res.json({
                code: 0,
                msg: '登录成功',
                data: token
            })
        } else {
            // 登录失败
            res.json({
                code: 2001,
                msg: '用户名或者密码错误',
                data: null
            })
            return;
        }
    }, err => {
        // 查询失败
        res.json({
            code: 500,
            msg: '查询失败',
            data: null
        })
        return;
    })
});

// 退出登录
router.post('/logout', function (req, res, next) {
    // 清除session
    req.session.destroy(() => {
        res.render('success', { msg: '退出成功', url: '/auth/login' });
    })
});

module.exports = router;
